// pages/makeSnapshot/makeSnapshot.js
const app=getApp()
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mode: 'dateTime',
    index:0,
    count: 3,
    latitude: 0, //首次加载维度
    longitude: 0, //首次加载的经度
    eventType:null,//事件类型
    location: "", //定位的位置
    time:0,//时间
    name:"",
    phone:"",
    desc:"",
    accounts: [ // value传给后台的值 ， label页面上显示的文字
      {value:'environment', label:'环境卫生'},
      {value:'traffic', label:'交通秩序'},
      {value:'advice', label:'建言献策'},
      {value:'progress', label:'乡风文明'},
      {value:'management', label:'圩镇管理'},
        ],
    imgs: [],
    reply:"",
    //获取当前item
    id:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id:options._id
    })
    db.collection('snapShot').doc(this.data.id).get().then(res=>{
      this.setData({
        eventType:res.data.eventType,
        time:res.data.time,
        location:res.data.location,
        phone:res.data.phone,
        name:res.data.name,
        desc:res.data.descri,
        imgs:res.data.photoUrl,
        reply:res.data.reply
      })
    })
  },

   // 下拉切换事件类型
   bindAccountChange(e){
        this.setData({
          eventType: this.data.accounts[e.detail.value].label
        })
  },
  onPickerChange(e) {//返回回调函数
      this.data.time=e.detail.value;
},
  //选择日期
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  //定位
  moveToLocation() {
    let that = this
    wx.chooseLocation({
        success: function (res) {
            //赋值给data中的location
            that.setData({
              location: res.name
            })
        },
        //错误信息
        fail: function () {
            console.log(err);
        }
    })
},
chooseImage: function (e) {
  wx.chooseImage({
    sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
    sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
    success: res => {
      const imgs = this.data.imgs.concat(res.tempFilePaths)
      this.setData({
        imgs: imgs
      })
    }
  })
},
bindUpload: function (e) {
  switch (this.data.imgs.length) {
    case 0:
      this.data.count = 3
      break
    case 1:
      this.data.count = 2
      break
    case 2:
      this.data.count = 1
      break
  }
  var that = this
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths
      for (var i = 0; i < tempFilePaths.length; i++) {
        wx.cloud.uploadFile({
          cloudPath:Date.now() + ".jpg",
          filePath: tempFilePaths[i],
          name: "file",
          header: {
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            if (res.statusCode == 200) {
              wx.showToast({
                title: "上传成功",
                icon: "none",
                duration: 1500
              })
              that.data.imgs.push(JSON.parse(res.data).data)

              that.setData({
                imgs: that.data.imgs
              })
            }
          },
          fail: function (err) {
            wx.showToast({
              title: "上传失败",
              icon: "none",
              duration: 2000
            })
          },
          complete: function (result) {
            console.log(result.errMsg)

          }
        })
      }
},
// 删除图片
deleteImage: function (e) {
  var that = this
  wx.showModal({
    title: "提示",
    content: "是否删除",
    success: function (res) {
      if (res.confirm) {
        for (var i = 0; i < that.data.imgs.length; i++) {
          if (i == e.currentTarget.dataset.index) that.data.imgs.splice(i, 1)
        }
        that.setData({
          imgs: that.data.imgs
        })
      } else if (res.cancel) {
      }
    }
  })
},
//放大预览图片
handleImagePreview(e) {
  const idx = e.target.dataset.idx
  const imgs = this.data.imgs
  wx.previewImage({
    current: imgs[idx], //当前预览的图片
    urls: imgs, //所有要预览的图片
  })
},
//提交
bindSubmit:function(e){
for (const key in this.data) {
  if(this.data[key]===""){
    wx.showToast({
      title: '不能有未填项！',
      icon: 'error',
      duration: 4000
    }) 
    return
  }
  if(key==="phone"){
    if(this.data.phone.length<8||(!/^\d+$/.test(parseInt(this.data.phone)))){
      wx.showToast({
        title: '手机格式错误，请重新填写',
        icon: 'error',
        duration: 4000
      })
      return   
    }
  }
}
db.collection('snapShot').doc(this.data.id).update({
  // data 字段表示需新增的 JSON 数据
  data: {
    eventType:this.data.eventType,
    location:this.data.location,
    time:this.data.time,
    name:this.data.name,
    phone:this.data.phone,
    descri:this.data.desc, 
    photoUrl:this.data.imgs,
    state:0,
  },
  
  success:(res)=> {
    // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
    wx.showToast({
      title: '提交成功！',
      icon: 'success',
      duration: 2000
    })
    setTimeout(()=>{
      wx.navigateBack({})
    },2000)
  }
})
}
})